<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'upload1.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <%
     //1. 创建FileItemFactory对象
     DiskFileItemFactory factory = new DiskFileItemFactory(); 
     //2. 创建ServletFileUpload对象 
     ServletFileUpload sfu =new ServletFileUpload(factory);
     //中文文件名乱码 
     sfu.setHeaderEncoding("utf-8");
     //3. 判断是否文件上传表单
     if( !ServletFileUpload.isMultipartContent(request) ){
    	 out.println("请修改表单的enctype=multipart/form=data");
     }else{
    	 //4. 解析form表单中所有组件 
    	List<FileItem>  list =  sfu.parseRequest(request);
    	out.println("表单中包括的组件的数量:"+list.size()+"<br/>");
		//5.遍历所有的表单组件 
		for(FileItem fileItem : list){
			if( fileItem.isFormField() ){
				//普通表单组件
				String name = fileItem.getFieldName();
				String value = fileItem.getString();
				out.println(name+"-->"+value+"<br/>");
			}else{
				//文件域:上传文件 
				//1.指定上传文件的地址 
				String name  = fileItem.getName();
				//1.1指定允许上传的扩展名
				List<String> ext = Arrays.asList(".jpg",".png",".bmp",".gif");
				//1.2 得到上传的文件的扩展名  Animal.txt
				String extName = name.substring( name.lastIndexOf(".")  );
				if( ! ext.contains( extName ) ){
					out.println(extName+"文件类型不允许上传...呵呵.");
				}else{
					String uploadPath=application.getRealPath("myFile");
					//2.创建一个空文件 
					File file = new File(uploadPath,name);
					//3.把上传的文件写到空文件 
					fileItem.write(file);
				}
			}
			
		}
    	 
     }
   	
   
   
   %>
   
   
  </body>
</html>
